import { useState, useCallback, useEffect } from 'react';
import { message } from 'antd';
import { platformRolesApi } from '../../services/platform/api/platformRolesApi';
import { useAsyncState } from '../common/useErrorHandler';
import type { PlatformRole } from '../../types/platform';
import type { PageResponse } from '../../services/api';

// 角色查询参数
export interface RoleQuery {
  search?: string;
  status?: number;
  current?: number;
  size?: number;
  isBuiltin?: boolean;
}

// 平台角色表单数据
export interface PlatformRoleFormData {
  id?: string;
  name: string;
  code: string;
  description?: string;
  status?: number;
  permissionCodes?: string[];
  sort?: number;
}

// 分页状态
interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

export const usePlatformRoles = () => {
  const { executeAsync, hasAnyLoading, error } = useAsyncState();
  
  // 状态管理
  const [roles, setRoles] = useState<PlatformRole[]>([]);
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState<string>('');

  // 加载角色列表（对齐usePlatformUsers架构：无参，依赖当前状态）
  const loadRoles = useCallback(async () => {
    return executeAsync('loadRoles', async () => {
      const response = await platformRolesApi.getRoles({
        current: pagination.current,
        size: pagination.pageSize,
        search: searchText,
      });

      setRoles(response.records || []);
      setPagination(prev => ({
        ...prev,
        total: response.totalElements || 0,
        // 仅在服务端提供不同页码时同步，否则保持现有current避免触发不必要的重新加载
        current: (response.number + 1) || prev.current,
      }));

      return response;
    });
  }, [executeAsync, pagination.current, pagination.pageSize, searchText]);

  // 获取角色详情
  const getRoleDetail = useCallback(async (roleId: string | number) => {
    return executeAsync('getRoleDetail', async () => {
      return await platformRolesApi.getRole(roleId);
    });
  }, [executeAsync]);

  // 创建角色
  const createRole = useCallback(async (roleData: PlatformRoleFormData) => {
    return executeAsync('createRole', async () => {
      const data = {
        ...roleData,
        id: undefined, // 创建时不需要id
      };
      await platformRolesApi.createRole(data);
      message.success('角色创建成功');
      await loadRoles();
    });
  }, [executeAsync, loadRoles]);

  // 更新角色
  const updateRole = useCallback(async (roleId: string | number, roleData: PlatformRoleFormData) => {
    return executeAsync('updateRole', async () => {
      const data = {
        ...roleData,
        id: undefined, // 更新时id通过参数传递
      };
      await platformRolesApi.updateRole(roleId, data);
      message.success('角色更新成功');
      await loadRoles();
    });
  }, [executeAsync, loadRoles]);

  // 删除角色
  const deleteRole = useCallback(async (roleId: string | number) => {
    return executeAsync('deleteRole', async () => {
      await platformRolesApi.deleteRole(roleId);
      message.success('角色删除成功');
      await loadRoles();
    });
  }, [executeAsync, loadRoles]);

  // 切换角色状态
  const toggleRoleStatus = useCallback(async (roleId: string | number, status: 'active' | 'inactive') => {
    return executeAsync('toggleRoleStatus', async () => {
      await platformRolesApi.toggleRoleStatus(roleId, status);
      message.success('状态更新成功');
      await loadRoles();
    });
  }, [executeAsync, loadRoles]);

  // 检查角色编码是否存在
  const checkRoleCodeExists = useCallback(async (code: string, excludeId?: string | number) => {
    return executeAsync('checkRoleCodeExists', async () => {
      const result = await platformRolesApi.checkRoleCodeExists(code, excludeId);
      return result.exists;
    });
  }, [executeAsync]);

  // 获取所有权限
  const getAllPermissions = useCallback(async () => {
    return executeAsync('getAllPermissions', async () => {
      return await platformRolesApi.getAllPermissions();
    });
  }, [executeAsync]);

  // 获取所有角色
  const getAllRoles = useCallback(async () => {
    return executeAsync('getAllRoles', async () => {
      return await platformRolesApi.getAllRoles();
    });
  }, [executeAsync]);

  // 搜索处理
  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  // 分页处理
  const handlePageChange = useCallback((page: number, pageSize?: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize,
    }));
  }, []);

  // 重置搜索
  const resetSearch = useCallback(() => {
    setSearchText('');
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  // 刷新数据
  const refresh = useCallback(() => {
    return loadRoles();
  }, [loadRoles]);

  // 分页或搜索条件变化时加载（含初次渲染）
  useEffect(() => {
    loadRoles();
  }, [pagination.current, pagination.pageSize, searchText]);

  return {
    // 状态
    roles,
    pagination,
    searchText,
    loading: hasAnyLoading,
    error,
    
    // 操作方法
    loadRoles,
    getRoleDetail,
    createRole,
    updateRole,
    deleteRole,
    toggleRoleStatus,
    checkRoleCodeExists,
    getAllPermissions,
    getAllRoles,
    
    // 工具方法
    handleSearch,
    handlePageChange,
    resetSearch,
    refresh,
  };
};

export default usePlatformRoles;